
import 'package:ble2025_plugin/ble2203_plugin.dart';
import 'package:ble2025_plugin_example/pages/alarm_clock_page.dart';
import 'package:ble2025_plugin_example/util/app_all_value.dart';
import 'package:ble2025_plugin_example/util/event_bus.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_utils/get_utils.dart';

///闹钟列表
class AlarmClockListPage extends StatefulWidget {
  const AlarmClockListPage({Key? key}) : super(key: key);

  @override
  State<AlarmClockListPage> createState() => _AlarmClockListPageState();
}

class _AlarmClockListPageState extends State<AlarmClockListPage> {

  int ModeStart = 0;
  int ModeContinue = 2;
  int ModeDelete = 0x99;

  bool isDelete = false;

  List<Clock> clocks = [];

  AppAllValueController controller = Get.find();

  @override
  void initState() {
    super.initState();
    EventBus().on('dataCallBack', (arg) {
      Map maps = arg;
      switch(maps[DeviceKey.DataType] as String){
        case BleConst.SetAlarmClockWithAllClock:
          break;
        case BleConst.GetAlarmClock:
          clocks.clear();
          List<Map> mapValue = maps[DeviceKey.Data] as List<Map>;
          for (Map map in mapValue) {
            String week = map[DeviceKey.Week].toString();
            List<String> weekString = week.split("-");
            var c = Clock( number:  int.parse(map[DeviceKey.KAlarmId]),
              type: int.parse(map[DeviceKey.ClockType]),
              hour: int.parse(map[DeviceKey.ClockTime]),
              minute: int.parse(map[DeviceKey.KAlarmMinter]),
              content: map[DeviceKey.KAlarmContent].toString(),
              enable: int.parse(map[DeviceKey.OpenOrClose]) == 1,
              weeks: weekString,);
            clocks.add(c);
          }
          setState(() {
          });
          break;
      }
    });
    controller.writeData(BleSDK.GetAlarmClock(ModeStart));
  }



  @override
  void dispose() {
    super.dispose();
    EventBus().off('dataCallBack');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("闹钟".tr),
      ),
      body: Column(
        mainAxisSize: MainAxisSize.max,
        children: [
          Row(
            children: [
              Expanded(child: Container(
                margin: const EdgeInsets.only(left: 10,right: 10),
                child: ElevatedButton(
                  child: Text('添加'.tr),
                  onPressed: (){
                    Get.to(AlarmClockPage())!.then((value){
                      //添加返回
                      if(value != null){
                        clocks.add((value as Clock));
                        updateClocks(clocks);
                        // controller.writeData(BleSDK.GetAlarmClock(ModeStart));
                      }
                    });
                  },
                ),
              )),
              Expanded(child: Container(
                margin: const EdgeInsets.only(right: 10),
                child: ElevatedButton(
                  child: Text('编辑'.tr),
                  onPressed: (){
                    setState(() {
                      isDelete = !isDelete;
                    });
                  },
                ),
              ))
            ],
          ),
          Expanded(child: clocks.isEmpty?Container(
            alignment: Alignment.center,
            child: Text('无数据'.tr),
          ):ListView.builder(
            shrinkWrap: true,
            itemCount: clocks.length,
            itemBuilder: (context,index){
              return buildItem(index);
            },

          ))
        ],
      ),
    );
  }

  ///更新闹钟数据
  ///Update alarm data
  void updateClocks(List<Clock> clocks){
    for (int i = 0; i < clocks.length; i++) {
      Clock clock = clocks[i];
      clock.number = i;
    }
    List<int> value = clocks.isEmpty ? BleSDK.deleteAllClock():BleSDK.setClockData(clocks);
    int maxLength = 200;
    if (value.length > maxLength) {//如果闹钟数据太长无法发送
      int size = maxLength ~/ 38;//一个包最多发的闹钟个数
      int length = size * 38;//最大闹钟数占用的字节
      int count = value.length % length == 0 ? value.length ~/ length : value.length ~/ length + 1;//需要多少个包来发送
      for (int i = 0; i < count; i++) {
        int end = length * (i + 1);
        int endLength = length;
        if (end >= value.length) endLength = value.length - length * i;
        List<int> data = List<int>.generate(endLength, (index) => 0);
        BleSDK.arrayCopy(value, length * i, data, 0, endLength);
        controller.offerValue(data);
      }
      controller.offerData();
    } else {
      controller.writeData(Uint8List.fromList(value));
    }
    Future.delayed(const Duration(seconds: 1),(){
      controller.writeData(BleSDK.GetAlarmClock(ModeStart));
    });
  }

  Widget buildItem(int index){
    return GestureDetector(
      onTap: (){
        Get.to(AlarmClockPage(clock: clocks[index],))!.then((value){
          ///编辑返回
          if(value != null){
            clocks[index] = (value as Clock);
            updateClocks(clocks);
          }
        });
      },
      child: SizedBox(
        height: 80,
        child: Column(
          mainAxisSize: MainAxisSize.max,
          children: [
            Expanded(child: Stack(
              children: [
                isDelete?GestureDetector(
                  onTap: (){
                    //删除
                    controller.showContentDialogTitle('提示'.tr, '是否要删除该闹钟?'.tr,onConfirm: (){
                      clocks.removeAt(index);
                      updateClocks(clocks);
                    });
                  },
                  child: Container(
                    color: Colors.white,
                    alignment: Alignment.centerLeft,
                    margin: const EdgeInsets.only(top: 10,left: 10),
                    child: const Icon(Icons.delete,color: Colors.red,),
                  ),
                ):Container(),
                Container(
                  color: Colors.white,
                  alignment: Alignment.topLeft,
                  margin: EdgeInsets.only(top: 10,left: isDelete?40:0),
                  child: Text('  ${clocks[index].hour.toString().length < 2 ? '0${clocks[index].hour}':clocks[index].hour}:${clocks[index].minute.toString().length < 2 ? '0${clocks[index].minute}':clocks[index].minute}',style: const TextStyle(fontSize: 20),),
                ),
                Container(
                  alignment: Alignment.bottomLeft,
                  margin: EdgeInsets.only(bottom: 10,left: isDelete?40:0),
                  child: Text('  ${weekString(clocks[index].weeks)}',),
                ),
                Align(
                  alignment: Alignment.centerRight,
                  child: Switch(
                    value: clocks[index].enable, onChanged: (bool value) {  },
                  ),
                ),
              ],
            )),
            Container(
              height: 1,
              color: Colors.blue,
            )
          ],
        ),
      ),
    );
  }

  String weekString(List<String> weeks){
    List<String> ws = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
    String text = '';
    for(int i = 0; i < weeks.length; i++){
      if(weeks[i] == '1'){
        text += "${ws[i].tr}、";
      }
    }
    text = text.substring(0,text.length - 1);
    return text;
  }

}
